package com.example.spring_forum.services.impl;

import com.example.spring_forum.common.AppResult;
import com.example.spring_forum.common.ResultCode;
import com.example.spring_forum.dao.BoardMapper;
import com.example.spring_forum.exception.ApplicationException;
import com.example.spring_forum.exception.model.Board;
import com.example.spring_forum.services.IBoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class BoardServiceImpl implements IBoardService {

    @Resource
    private BoardMapper boardMapper;

    @Override
    public List<Board> selectByNum(Integer num) {

         if(num == null || num <= 0){
             //打印日志
             log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
             //抛出异常
             throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
         }

         //调用dao

        List<Board> result=boardMapper.selectByNum(num);

        return result;
    }

    @Override
    public Board selectById(Long id) {


        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
           //调用dao
           Board board= boardMapper.selectByPrimaryKey(id);
        return board;
    }

    @Override
    public void  addOneArticleCountById(Long id) {

        //非空校验

        if(id == null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        //查询板块信息
        Board board=selectById(id);
        //校验板块是否存在
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //构造要更新的对象
        Board updateBoard=new Board();
        updateBoard.setId(board.getId()); //板块Id
        updateBoard.setArticleCount(board.getArticleCount()+1); //帖子数量
        updateBoard.setUpdateTime(new Date());//更新时间

         int row=boardMapper.updateByPrimaryKeySelective(updateBoard);
         if(row!=1){
             //打印日志
             log.warn(ResultCode.ERROR_SERVICES.toString());
             //抛出异常
             throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
         }

    }
}
